package controller.intercepter;

import constant_tools.TokenUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class FileInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setCharacterEncoding("utf-8");

        String url = request.getRequestURI();
        System.out.println(url);

        if(!url.endsWith("users/login")){
            System.out.println("非登录页面。。。");

            if (request.getRequestURI().contains("/users/login")) {
                return true;
            }

            //放行OPTIONS请求
            String method = request.getMethod();
            if ("OPTIONS".equals(method)) {
                return true;
            }

            //从http请求头中取出token（后面前端会将token内容存入Headers中）
            String token = request.getHeader("Authorization");
            System.out.println(token);
            if(token.equals("null"))
                return false;
            //执行认证
            return TokenUtils.verify(token);
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
